package cz.proks.schoolpupilbook.gae.converter;

import com.google.appengine.api.datastore.KeyFactory;

import cz.proks.schoolpupilbook.gae.dao.UserDAO;
import cz.proks.schoolpupilbook.gae.dbo.UserRelationDBO;
import cz.proks.schoolpupilbook.shared.domain.User;
import cz.proks.schoolpupilbook.shared.domain.UserRelation;
import cz.proks.schoolpupilbook.shared.util.Tester;

public class UserRelationConverter implements Converter<UserRelationDBO, UserRelation>{
	@Override
	public UserRelationDBO getDBO(UserRelation domain) {
		if (domain == null)
			return null;
		
		UserRelationDBO dbo = new UserRelationDBO();
		
		if (!Tester.isEmpty(domain.getId()))
			dbo.setId(KeyFactory.stringToKey(domain.getId()));
		
		dbo.setParentKey(KeyFactory.stringToKey(domain.getParent().getId()));
		dbo.setStudentKey(KeyFactory.stringToKey(domain.getStudent().getId()));
		
		return dbo;
	}

	@Override
	public UserRelation getDomain(UserRelationDBO dbo) {
		if (dbo == null)
			return null;
		
		UserDAO dao = new UserDAO();
		User parent = dao.find(dbo.getParentKey());
		User student = dao.find(dbo.getStudentKey());
		
		UserRelation domain = new UserRelation();
		domain.setId(KeyFactory.keyToString(dbo.getId()));
		domain.setParent(parent);
		domain.setStudent(student);
		
		return domain;		
	}
}
